package aufgabe2_pop3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import speicherorte.Speicher_Orte;

public class Mailverwaltung {

	private SimpleDateFormat simple = new SimpleDateFormat("ddMMyyyyHHmmss");
	
	private HashMap<Integer, String> mailMap;
	private HashMap<Integer, Integer> size;
	private List<Integer> delete;

	private int mailID;

	public Mailverwaltung(Datenbank datenbank) {
		initFolder();
		mailMap = load_mail_map(Speicher_Orte.persistencefolder);
		mailID = mailMap.size();
		size = new HashMap<Integer, Integer>();
		delete = new ArrayList<Integer>();
	}

	private String getTimestampFromMail(int id) {
		return mailMap.get(id);
	}

	public boolean idVorhanden(int id) {
		return mailMap.containsKey(id) && !delete.contains(id);
	}

	/**
	 * Speichert Eine Mail
	 * @param mailContent List<String> Der Mail in Zeilen
	 */
	public void saveMail(List<String> mailContent) {
		// Holen der Systemzeit
		Timestamp time = new Timestamp(System.currentTimeMillis());
		String daytime = simple.format(time);

		PrintWriter writer;
		int length = 0;

		// Anlegen einer Textdatei mit dem Namen und Speicher der Mail
		try {
			writer = new PrintWriter(new BufferedWriter(new FileWriter(Speicher_Orte.emailfolder + daytime + ".txt")));
			for (String line : mailContent) {
				if (line.startsWith(".")) {
					line = line.replaceFirst(".", "");
				}
				writer.println(line);
				length = length + line.length();
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//Datenbank aktuallisieren
		mailID++;
		size.put(mailID, length);
		mailMap.put(mailID, daytime);
		save_mail_map();
	}

	/**
	 * Lesen einer Mail
	 * 
	 * @param id int ID der Mail   
	 * @return List<String> Der Mail in Zeilen
	 */
	public ArrayList<String> read_Mail(int id) {

		ArrayList<String> mail = new ArrayList<String>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(Speicher_Orte.emailfolder + mailMap.get(id) + ".txt"));
			String line;
			
			line = reader.readLine();
			while (line != null) {
				if (line.startsWith(".")) {
					line = "." + line;
				}
				mail.add(line);
				line = reader.readLine();
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mail;
	}

	public Long oktasize(int id) {
		File file = new File(Speicher_Orte.emailfolder + mailMap.get(id));
		return file.length();
	}

	public void rset() {
		delete.clear();
	}

	public void dele(int id) {
		delete.add(id);
	}

	public List<Integer> id_list() {
		Set<Integer> keys = mailMap.keySet();
		return new ArrayList<Integer>(keys);
	}

	public String uidl(Integer integer) {
		return integer.toString() + " " + getTimestampFromMail(integer).toString();
	}

	public String stat() {
		List<Integer> sizemap = new ArrayList<Integer>(size.values());
		Integer allmailsize = 0;
		
		for (Integer mailsize : sizemap) {
			allmailsize = allmailsize + mailsize;
		}

		return ("+OK " + mailMap.size() + " " + allmailsize.toString());
	}

	public void quit() {
		
		for(Integer id : delete){ mailMap.remove(id); File file = new
		File(Speicher_Orte.emailfolder + mailMap.get(id)); file.delete(); }
		
		delete.clear();
		save_mail_map();
	}

	/**
	 * Speichert die Aktuelle Mail Map
	 * @param ort Der Ort
	 * @param map Die Map
	 */
	  	private void save_mail_map() {
	 
		try {
			PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(Speicher_Orte.persistencefolder + "mails.txt")));

			List<String> usid_list = new ArrayList<String>(mailMap.values());

			for (String usid : usid_list) {
				writer.println(usid);
			}

			writer.flush();
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Laedt eine Gespeicherte Mail map oder erstellt eine neue.
	 * 
	 * @param ort
	 *            Der Ort und Name der Datei
	 * @return Die Mailmap
	 */
	private HashMap<Integer, String> load_mail_map(String ort) {
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		int id = 0;

		try {

			BufferedReader reader = new BufferedReader(new FileReader(ort
					+ "mails.txt"));
			String usid = reader.readLine();

			while (usid != null) {
				id++;
				map.put(id, usid);
				usid = reader.readLine();
			}

			reader.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	private void initFolder() {
		File dataFile = new File(Speicher_Orte.datafolder);
		File mailFile = new File(Speicher_Orte.emailfolder);
		File logFile = new File(Speicher_Orte.logfolder);
		File persistenceFile = new File(Speicher_Orte.persistencefolder);
		File mailMapDatei = new File(Speicher_Orte.persistencefolder
				+ "mails.txt");

		dataFile.mkdir();
		mailFile.mkdir();
		logFile.mkdir();
		persistenceFile.mkdir();
		try {
			mailMapDatei.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
